const { ipcMain } = require('electron');
const SchemaEngine = require('../services/SchemaEngine');
const logger = require('../utils/logger');
const { getMainKnex, getCaseKnex } = require('../database/knex');

let schemaEngine;

module.exports = {
    setupSchemaHandlers: () => {
        const knex = getMainKnex();
        schemaEngine = new SchemaEngine(knex);

        schemaEngine.init().catch(err => {
            logger.error(`Failed to initialize SchemaEngine: ${err.message}`);
        });

        ipcMain.handle('schema:get-all', async () => {
            try {
                return await schemaEngine.getSchemas();
            } catch (error) {
                logger.error(`IPC schema:get-all failed: ${error.message}`);
                throw error;
            }
        });

        ipcMain.handle('schema:get-by-name', async (event, name) => {
            try {
                return await schemaEngine.getSchemaByName(name);
            } catch (error) {
                logger.error(`IPC schema:get-by-name failed: ${error.message}`);
                throw error;
            }
        });

        ipcMain.handle('schema:sync', async () => {
            try {
                return await schemaEngine.syncExistingTables();
            } catch (error) {
                logger.error(`IPC schema:sync failed: ${error.message}`);
                throw error;
            }
        });

        // 同步案件数据库表
        ipcMain.handle('schema:sync-case', async (event, caseId, dbPath) => {
            try {
                const caseKnex = getCaseKnex(caseId, dbPath);
                return await schemaEngine.syncCaseTables(caseKnex, caseId);
            } catch (error) {
                logger.error(`IPC schema:sync-case failed: ${error.message}`);
                throw error;
            }
        });

        ipcMain.handle('schema:create', async (event, schemaDef) => {
            try {
                return await schemaEngine.createSchema(schemaDef);
            } catch (error) {
                logger.error(`IPC schema:create failed: ${error.message}`);
                throw error;
            }
        });

        ipcMain.handle('schema:update', async (event, name, changes) => {
            try {
                return await schemaEngine.updateSchema(name, changes);
            } catch (error) {
                logger.error(`IPC schema:update failed: ${error.message}`);
                throw error;
            }
        });

        ipcMain.handle('schema:delete', async (event, name, dropTable) => {
            try {
                return await schemaEngine.deleteSchema(name, dropTable);
            } catch (error) {
                logger.error(`IPC schema:delete failed: ${error.message}`);
                throw error;
            }
        });
    }
};
